<?php
class login
{
	/*
	 * run this function at the top of every page
	 * it checks for a cookie to see if someone is logged in
	 * else checks for action to see if just logged in
	 * if not logged in, display the login form
	 * 
	 */
	static function displayLoginDiv()
	{
		// if cookie
		if(isset($_COOKIE['BuffBoardCookie']))
			login::displayLoginUsername();
		//else check login action
		else
		{
			$loggedIn = login::loginAction();
			
			if($loggedIn)
				login::displayLoginUsername();
			else
				login::displayLoginForm();
		}
	}
	
	/*
	 * This function is responsible for logging the user in
	 * It takes the username and password from the login form
	 * and checks tje creds against the database
	 * if they are correct, it sets a cookie with the user 
	 * information, and returns true
	 * if the creds were not correct, nothing will happen and 
	 * it will return false
	 */
	static function loginAction()
	{
		if(!empty($_POST['action']))
		{
			if($_POST['action'] == 'login')
			{
				$username = mysql_real_escape_string($_POST['username']);
				$password = mysql_real_escape_string($_POST['password']);
				
				$success = userClass::loginUser($username, $password);
				if($success)
				{
					//store cookie
					$ID = userClass::getIDByUsername($username);
					setcookie("BuffBoardCookie", $ID, time()+3600*24*30);
					//echo 'set cookie<br/>';
					
					return true;
				}
				else
				{
					//echo 'did not set cookie<br/>';
					return false;
				}
			}
			return false;
		}
		return false;
	}
	
	/*
	 * If the user is not logged in, the form will display
	 * 
	 * This function displays the login form directly onto the page
	 */
	static function displayLoginForm()
	{
	?>
		<form id="headerLoginForm" name="headerLoginForm" action="logUserIn.php" method="post">
			<div style="float:left;">
				<label for="usernameLogin">Username:</label>
					<input type="text" class="text" id="usernameLogin" name="username" />
				<br/>
				<label for="passwordLogin">Password:</label>
					<input type="password" class="text" id="passwordLogin" name="password" />
				
			</div>
			<div style="float:right;">
				<a href="newuser.php">Create an account</a><br/>
				<br/>
				
				<input type="hidden" name="action" value="login" />
				<input type="submit" class="submit" value="Login"/>
			</div>
		</form>
	<?php 
	}
	
	/*
	 * If the user is logged in, there usernam will be displayed instead
	 * 
	 * This function retreives their username and displays it directly
	 * to the page
	 */
	static function displayLoginUsername()
	{
		//access cookie
		$name = userClass::getUsernameByID(mysql_real_escape_string($_COOKIE["BuffBoardCookie"]));
		
		//print name
		echo "<h3>Hello $name </h3>";
	}
	
	
	/*
	 * This function will delete the cookie for the user
	 */
	static function logoutAction()
	{
		setcookie("BuffBoardCookie", "", time()-3600);
	}
}